mini.parse();
var projectName = mini.get("projectName").getValue();
var taskKey = mini.get("taskKey").getValue();
var listGrid = mini.get("equipment_list_datagrid");
var conGrid = mini.get("equipment_list_confirm_datagrid");
var in_org_name = mini.get("in_org_name");
var in_org_id = mini.get("in_org_id");
var org_id = mini.get("org_id");
var storage_addr = mini.get("storage_addr");
var storage_addr_id = mini.get("storage_addr_id");
var storage_name = mini.get("storage_name");
var storage_id = mini.get("storage_id");
var storage_attr = mini.get("storage_attr");
var storage_people_name = mini.get("storage_people_name");
var storage_people_id = mini.get("storage_people_id");
var check_people_id = mini.get("check_people_id");
var orgId = '';
var physicalStorageId = '';
var storageId = '';
var url = '';
var person = '';

function beforeSend(){
	if(taskKey == 'start' || taskKey == 'usertask1'){
		queryCheckPeople();
		if(!checkGrid(listGrid)) return false;
		if(!checkCheckPeople()) return false;
		if (!verifyCount(buildVerifyCountParam(listGrid, "1"))) {
			return false;
		}
	}
	if(taskKey == 'usertask2'){
		var result = mini.get("check_result").getValue();
		if (result == '1') {
			copyListTo();
        }else{
        	delRow_all(listGrid,'1');
        }
	}
	if(taskKey == 'usertask3'){
		if(!checkGrid(conGrid)) return false;
		if(!compareGrid()) return false;
		if (!verifyCount(buildVerifyCountParam(conGrid, "0"))) return false;
		if (!checkInstallbarcode()) {
			return false;
		}
		if (!checkBarcodeStatus(mini.get("wo_no").getValue(),"", "1")) {
			return false;
		}
	}
	return true;
}
/** 提交验证条码状态**/
function checkBarcodeStatus(businessKey,storageNumId,statusNumId){
	var flag = true;
	$.ajax({
		url:projectName+'/InventoryEqAdmin/checkBarcodesForSubmit',
		type:'post',
		dataType:'json',
		cache:false,
		async:false,
		data:{businessNo:businessKey,storageNumId:storageNumId,statusNumId:statusNumId},
		success: function(response){
			if (response.status == "1") {
				flag =  true;
			}else{
				mini.alert(response.message);
				flag =  false;
			}
		},error:function(){
			mini.alert("验证条码状态请求失败");
			flag =  false;
		}
	});
// 验证数量
function verifyCount(data) {
	var flag = false;
	$.ajax({
		url : projectName + '/PurBarcodeAdmin/validateCount',
		type : 'post',
		dataType : 'json',
		cache : false,
		async : false,
		data : {list : data},
		success : function(response) {
			if (response.status == "1") {
				flag = true;
			} else {
				mini.alert(response.message);
			}
		},
		error : function() {
			mini.alert("验证条码数量请求失败");
		}
	});
	return flag;
}

//组建表数据
function buildVerifyCountParam(grid, statusNumId) {
	var arr = [];
	var griddata = grid.getData();
	for (var i = griddata.length - 1; i >= 0; i--) {
		var obj = {};
		obj.businessKey = mini.get("wo_no").getValue();
		obj.equipmentId = griddata[i].EQ_ID;
		obj.statusNumId = statusNumId;
		obj.num = griddata[i].EQ_NUM;
		arr.push(obj);
	}
	return mini.encode(arr);
}

//比较两个子表的数据是否相同
function compareGrid(){
	var data = listGrid.getData(); //入库数据
	var data1 = conGrid.getData(); //确认清单
	outer:
		for (var i = 0; i < data.length; i++) {
			var flag = false;
			inter:
			for (var j = 0; j < data1.length; j++) {
				if (data[i].EQ_ID == data1[j].EQ_ID){
					flag = true;
					break inter;
				}
			}
			if (!flag) {
				mini.alert("确认设备清单与入库设备清单不一致");
				return false;
			}
		}
		return true;
}

//入库设备清单同步到确认清单
function copyListTo(){
	delRow_all(conGrid,'0');
	var datalist = mini.clone(listGrid.getData());
	var dataCon = conGrid.getData();
	addDataToGrid(datalist,dataCon,conGrid);
}

// 筛选出需要添加到另一个表格的数据
function addDataToGrid(data,dataOther,grid){ // data 源表格数据  dataOther 目标表格数据  grid 目标表格
	for(var i=0; i<data.length ;i++){
		var outHas = false;
		for(var j=0; j<dataOther.length;j++){
			if(dataOther[j].EQ_ID == data[i].EQ_ID) outHas=true;
		}
		if(!outHas){
			grid.addRow(data[i]);
		}
	}
}

//查看入库设备条码
function queryBarCode1(_uid){
	var c = listGrid.getRowByUID(_uid);
	queryBarCode(c.EQ_ID, '1')
}

//查看确认设备条码
function queryBarCode2(_uid){
	var c = conGrid.getRowByUID(_uid);
	queryBarCode(c.EQ_ID, '0')
}

//编辑入库设备条码
function editBarCode1(_uid){
	editBarCode(listGrid,_uid,'1');
}

//编辑确认设备条码
function editBarCode2(_uid){
	editBarCode(conGrid,_uid,'0');
}

//查询条码
function queryBarCode(eqId, statusNumId){
	var businessKey = mini.get("wo_no").getValue();
	mini.open({
        url: projectName+"/PurBarcodeAdmin/barCodeEqIDView",
        title: '查看条码', width: 700, height: 500,
        onload: function () {
            var iframe = this.getIFrameEl();
            var data = {businessKey:businessKey,eqId:eqId,statusNumId:statusNumId};
            iframe.contentWindow.setData(data);
        }
    });
}

//编辑条码
function editBarCode(grid,uid,statusNumId){
	var businessKey = mini.get("wo_no").getValue();
	var c = grid.getRowByUID(uid);
	var eqId=c.EQ_ID;
	var eqTypeId=c.EQ_TYPE_ID;
	var data = {businessKey:businessKey,statusNumId:statusNumId,eqId:eqId,eqTypeId:eqTypeId};
	mini.open({
		url: projectName+"/PurBarcodeAdmin/otherAddSearchBar",
		title: '编辑条码', width: 700, height: 500,
		onload: function () {
			var iframe = this.getIFrameEl();
			iframe.contentWindow.setData(data);
		},
		ondestroy:function(){
			reloadGrid_(grid,data);
		}
	});
}


//删除确认清单
function delRow_con(){
	delRow_(conGrid,'0');
}

//删除入库设备清单
function delRow_list(){
	delRow_(listGrid,'1');
}

function delRow_(grid,statusNumId){
	var rows = grid.getSelecteds();
	if(rows.length < 1){
		mini.alert("请至少选择一条记录！");
		return;
	}
	for(var i=0; i<rows.length;i++){
		grid.removeRow(rows[i]);
		delBarcodeByBusKeyAndEqId(rows[i].EQ_ID,statusNumId);
	}
	if (statusNumId == '0') {
		
	}
	
}

function GetFormData(form_Name){
	var o = form_Name.getData();
	return o;
}

//删除设备条码
function delBarcodeByBusKeyAndEqId(eqId,statusNumId){
	var wono = mini.get("wo_no").getValue();
	if(wono){
		$.ajax({
			url:projectName+'/PurBarcodeAdmin/delBarcodeByBusKey',
			type:'post',
			dataType:'json',
			cache:false,
			async:false,
			data:{businessKey: wono,equipmentId:eqId,statusNumId:statusNumId},
			success: function(response){
				if (response.status == "1") {
				}else{
					mini.alert("清除设备条码出错！");
				}
			},
			error:function(){
				mini.alert("出错啦!");
			}
		})
	}else{
		mini.alert("未获取到入库单号！");
	}
}

//新增入库设备清单  录入条码
function addEquipmentList(){
	if(velidateform2()){
		var businessKey = mini.get("wo_no").getValue();
		var statusNumId = "1";
		var data = {businessKey:businessKey,statusNumId:statusNumId};
		openEditBarCode(listGrid,data);
	}
}

//编辑条码页面
function openEditBarCode(grid,data){
	mini.open({
		 url: projectName+"/PurBarcodeAdmin/otherAddSearchBar",
		     title: "条码录入", width: 700, height: 500,
		     onload: function () {
		     var iframe = this.getIFrameEl();
	         iframe.contentWindow.setData(data);
	    },
	    ondestroy: function () {
	    	reloadGrid_(grid,data);
	    }
	});
}

//重新加载子表
function reloadGrid_(grid,data){
	var param = {businessKey:data.businessKey,statusNumId:data.statusNumId};
	$.ajax({
		url:projectName+'/PurBarcodeAdmin/statisticsBarcode',
		type:'post',
		dataType:'json',
		cache:false,
		async:false,
		data: param,
		success: function(response){
			if (response.status == "1") {
                grid.clearRows();
//				delRow_all(grid,'1');
				for (var i=0;i<response.result.equipment_list.length;i++) {
					var object = response.result.equipment_list[i];
					var record = {};
					record.EQ_ID = object.equipmentId;
					record.EQ_NAME = object.equipmentName;
					record.EQ_TYPE_ID = object.equipmentType;
					record.EQ_TYPE_NAME = object.equipmentTypeName;
					record.EQ_NUM = object.qty;
					grid.addRow(record);
				}
			}else{
//				mini.alert(response.message);
			}
		},
		error:function(){
			mini.alert("出错啦!");
		}
	});
}

//审核是否通过选择事件
function onSelectResult(e){
	var re = e.value;
	var c = mini.get("check_memo");
	if (re && re == '1') {
		c.setRequired(false);
		c.setEmptyText("");
		if (e.setIsValid)
			e.setIsValid(true);
	}
	if (re && re == '0') {
		mini.get("check_memo").setRequired(true);
		c.setEmptyText("请输入审批不通过的原因");
	}
}

//查询其它入库审核人员
function queryCheckPeople(){
	orgId = org_id.getValue();
	if(orgId){
		$.ajax({
			url : projectName + "/RoleUserAdmin/queryOtherCheck?orgId=" + orgId,
			dataType : 'json',
			async : false,
			success : function(data) {
				if (data.status == '1') {
					mini.get("check_people_id").setValue(data.message);
				} else {
					mini.alert("查询交接单审核人员出错!");
				}
			},
			error : function() {
				mini.alert("出错啦!");
			}
		});
	}
}

//校验子表非空
function checkGrid(grid){
	var data = grid.getData();
	if (data.length > 0)  return true;
	mini.alert("请添加子表设备信息");
	return false;
}

//校验审核人  客服经理
function checkCheckPeople(){
	var checkPeopleId = check_people_id.getValue();
	if(!checkPeopleId){
		mini.alert("系统中没有配置处理交接单审核的工作流人员，禁止提交！");
		return false;
	}
	return true;
}

//校验必填项
function velidateform2() {
	var form_temp = new mini.Form("form2");
	form_temp.validate();
	if (form_temp.isValid() == false) {
		return false;
	}
	return true;
}

var windowsFlag1 = false;
//选择仓库负责人时校验是否选择了逻辑仓
function onPersonCheck(){
	person = storage_id.getValue();
  	if(!person){
		if (!windowsFlag1) {
			mini.alert("请选择仓库", "", function() {
				windowsFlag1 = false;
			});
			windowsFlag1 = true;
		}
  	}
}

//选择逻辑仓时加载仓库负责人 给逻辑仓name赋值
function onStorageChange(){
	storage_name.setValue(storage_id.text);	
	var item = storage_id.getSelected();
	if(item.directorId){
		storage_attr.setValue(item.storageType);
		storage_people_name.setValue(item.directorName);
		storage_people_id.setValue(item.directorId);
	}else{
		mini.alert("该仓库没有指定仓库负责人！");
		return;
	}
}

var windowsFlag = false;
//选择逻辑仓时校验是否选择了物理仓
function onAddrCheck(){
	physicalStorageId = storage_addr_id.getValue();
	if(!physicalStorageId){
		if (!windowsFlag) {
			mini.alert("请选择仓库地点", "", function() {
				windowsFlag = false;
			});
			windowsFlag = true;
		}
	}
}

//逻辑仓改变时，加载物理仓
function onPhyStorageChange(){
	storage_addr.setValue(storage_addr_id.text);
	storage_name.setValue("");
	storage_id.setValue("");
	storage_people_name.setValue("");
	storage_people_id.setValue("");
	physicalStorageId = storage_addr_id.getValue();
    if(physicalStorageId){
		url = projectName + "/StStorageAdmin/findStStorageList?physicalStorageId=" + physicalStorageId;
		storage_id.load(url);
		var d = [];
		var da = storage_id.getData();
		for (var i = 0; i < da.length; i++) {
			var t = da[i].storageType;
			if(t == '1' || t == '2'){
				d.push(da[i]);
			}
		}
		storage_id.setData(d);
    }
}

var windowsFlag0 = false;
//选择物理仓时校验是否选择了组织机构
function onOrgCheck(){
	orgId = in_org_id.getValue();
	if(!orgId){
		if (!windowsFlag0) {
			mini.alert("请选择组织机构", "", function() {
				windowsFlag0 = false;
			});
			windowsFlag0 = true;
		}
    }
}

//组织机构改变时，加载该机构下的仓库
function onOrgChange(){
	in_org_name.setValue(in_org_id.text);
	storage_addr.setValue("");
	storage_addr_id.setValue("");
	storage_name.setValue("");
	storage_id.setValue("");
	storage_people_name.setValue("");
	storage_people_id.setValue("");
	orgId = in_org_id.getValue();
    if(orgId){
		url = projectName + "/PhyStorageAdmin/findPhyStorageList?orgId="+orgId+"&type=0";
		storage_addr_id.load(url);
    }
}

//校验必填项
function velidateform2() {
	var form_temp = new mini.Form("form2");
	form_temp.validate();
	if (form_temp.isValid() == false) {
		return false;
	}
	return true;
}

function delRow_all(grid,statusNumId){
	var rows = grid.getData();
	for(var i=0; i<rows.length;i++){
		grid.removeRow(rows[i]);
		delBarcodeByBusKeyAndEqId(rows[i].EQ_ID,statusNumId);
	}
}

//校验安装条码
function checkInstallbarcode(){
	var flag = false;
	var wono = mini.get("wo_no").getValue();
	$.ajax({
		url:projectName+'/PurBarcodeAdmin/checkInstallbarcode',
		type:'post',
		dataType:'json',
		cache:false,
		async:false,
		data:{businessKey: wono,statusNumId:'1'},
		success: function(response){
			if (response.status == "1") {
				flag =  true;
			}else{
				mini.alert(response.message);
			}
		},
		error:function(){
			mini.alert("出错啦!");
		}
	});
	return flag;
}
